package com.example.myapplication15_3;

import android.content.Context;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class StudentDataManager {
    private static final String TAG = "StudentDataManager";
    private static final String FILE_NAME = "students.json";
    private final Context context;

    public StudentDataManager(Context context) {
        this.context = context;
    }

    // 保存学生数据
    public boolean saveStudent(Student student) {
        List<Student> students = loadAllStudents();
        students.add(student);
        return saveStudentList(students);
    }

    // 保存学生列表
    private boolean saveStudentList(List<Student> students) {
        try {
            JSONArray jsonArray = new JSONArray();
            for (Student student : students) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", student.getName());
                jsonObject.put("score", student.getScore());
                jsonArray.put(jsonObject);
            }

            String jsonString = jsonArray.toString();
            FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
            fos.write(jsonString.getBytes());
            fos.close();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "保存数据失败: " + e.getMessage());
            return false;
        }
    }

    // 加载所有学生数据
    public List<Student> loadAllStudents() {
        List<Student> students = new ArrayList<>();
        
        try {
            File file = new File(context.getFilesDir(), FILE_NAME);
            if (!file.exists()) {
                return students; // 如果文件不存在，返回空列表
            }

            FileInputStream fis = context.openFileInput(FILE_NAME);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            isr.close();
            fis.close();

            String jsonString = sb.toString();
            if (jsonString.isEmpty()) {
                return students; // 如果文件为空，返回空列表
            }

            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name = jsonObject.getString("name");
                float score = (float) jsonObject.getDouble("score");
                students.add(new Student(name, score));
            }
        } catch (IOException | JSONException e) {
            Log.e(TAG, "加载数据失败: " + e.getMessage());
        }

        return students;
    }

    // 搜索学生
    public List<Student> searchStudentsByName(String keyword) {
        List<Student> allStudents = loadAllStudents();
        if (keyword == null || keyword.isEmpty()) {
            return allStudents;
        }

        List<Student> result = new ArrayList<>();
        for (Student student : allStudents) {
            if (student.getName().toLowerCase().contains(keyword.toLowerCase())) {
                result.add(student);
            }
        }
        return result;
    }
} 